/**
 * Created by Administrator on 2016/6/3.
 */
'use strict';
app.service('UserInfo', ['$http', '$q', 'UserInfoSession', 'UserInfoConstant', function ($http, $q, UserInfoSession, UserInfoConstant) {

    var authService = {};

    /**
     * 判断是否登陆
     * @returns {boolean}
     */
    authService.isAuthenticated = function () {
        return !!UserInfoSession.userId;
    };

    /**
     * 查询权限相关信息
     * @returns {d.promise|promise|AnimateRunner.promise|qFactory.Deferred.promise}
     */
    authService.flush = function () {
        var deferred = $q.defer();
        $http.get('index.do').success(function (res) {
            if (res.entity) {
                UserInfoSession.create(res.entity.id, res.entity.username, res. entity.authorities, res.entity);
            } else {
                UserInfoSession.create(res.entity, res.entity, [], {});
            }
            deferred.resolve(res);
        });
        return deferred.promise;
    }
    
    /**
     * 查询权限相关信息
     * @returns {d.promise|promise|AnimateRunner.promise|qFactory.Deferred.promise}
     */
    authService.get = function () {
    	var deferred = $q.defer();
        if(UserInfoSession.isInit) {
        	deferred.resolve("success");
        	return deferred.promise;
        }
        return authService.flush();
    }

    /**
     * 清理用户信息
     * @returns {*}
     */
    authService.cleanUserInfo = function () {
        return UserInfoSession.destroy();
    }

    /**
     * 获取权限相关实体
     * @returns {*}
     */
    authService.getEntity = function () {
        return UserInfoSession.entity;
    }


    /**
     * 判断权限是否具备
     * @param auth
     * @returns {boolean}
     */
    authService.isAuthorized = function (auth) {
        if (UserInfoConstant.IS_AUTHENTICATED_ANONYMOUSLY == auth) {
            return true;
        }
        if(!UserInfoSession.isInit) {
            // 先要初始化用户信息
            $.ajax({
                url : 'index.do',
                type : 'GET',
                async : false,
                success : function(res){
                    if (res.entity) {
                        UserInfoSession.create(res.entity.id, res.entity.username, res. entity.authorities, res.entity);
                    } else {
                        UserInfoSession.create(res.entity, res.entity, [], {});
                    }
                },
                dataType :  'json'})
        }
        if(authService.isAuthenticated()) {
            if (UserInfoConstant.IS_AUTHENTICATED_FULLY == auth && UserInfoSession.userId) {
                // 登录用户权限
                return true;
            }
            if(UserInfoSession.authorities){
                for (var i = 0; i < UserInfoSession.authorities.length; i++) {
                    var authority = UserInfoSession.authorities[i];
                    if (authority.authority === auth) {
                        return true;
                    }
                }
            }
        }
        return false;

    };
    
    /**
     * 判断是否匿名用户
     * @returns {boolean}
     */
    authService.isAnonymousUser = function () {
    	if(UserInfoConstant.anonymousUser === UserInfoSession.userName) {
    		return true;
    	}
        return false;
    };
    
    /**
     * 判断路由是否需要登录
     * @param state
     * @returns {boolean}
     */
    authService.isNeedLogin = function (targetState) {
    	if(UserInfoSession.userName && UserInfoConstant.anonymousUser !== UserInfoSession.userName) {
    		return false;
    	}
    	
        if (targetState && targetState.data && targetState.data.authorities && targetState.data.authorities.length > 0) {
            var authorities = targetState.data.authorities;
            for (var i = 0; i < authorities.length; i++) {
                var auth = authorities[i];
                if (auth === UserInfoConstant.IS_AUTHENTICATED_ANONYMOUSLY) {
                   return false;
                }
            }
        } 
        return true;
    };

    /**
     * 判断路由是否具备权限
     * @param state
     * @returns {boolean}
     */
    authService.isAuthorizedForState = function (targetState) {
        var hasAuth = false;
        if (targetState && targetState.data && targetState.data.authorities && targetState.data.authorities.length > 0) {
            var authorities = targetState.data.authorities;
            for (var i = 0; i < authorities.length; i++) {
                var auth = authorities[i];
                if (authService.isAuthorized(auth)) {
                    hasAuth = true;
                    break;
                }
            }
        } else {
            // 未配置权限不需要验证权限，直接通过
            hasAuth = true;
        }
        return hasAuth;
    };

    /**
     * 判断是否在组中
     * @param group
     * @returns {boolean}
     */
    authService.hasGroup = function (group) {
        return authService.isAuthorized(UserInfoConstant.PRE_GROUP + group) || authService.isAuthorized(group);
    };
    /**
     * 判断是否在组中
     * @param auth
     * @returns {boolean}
     */
    authService.hasAuth = function (auth) {
        return authService.isAuthorized(UserInfoConstant.PRE_AUTH + auth) || authService.isAuthorized(auth);
    };
    /**
     * 返回用户所有权限
     * @returns {boolean}
     */
    authService.getAuthorities = function () {
        return UserInfoSession.authorities;
    };


    return authService;
}]);
app.service('UserInfoSession', function () {
    this.create = function (userId, userName, authorities, entity) {
        this.userId = userId;
        this.userName = userName;
        this.authorities = authorities;
        this.entity = entity;
        this.isInit = true;
    };
    this.destroy = function () {
        this.userId = null;
        this.userName = null;
        this.authorities = [];
        this.entity = null;
        this.isInit = true;
    };
    return this;
}).constant('UserInfoConstant', {
    IS_AUTHENTICATED_ANONYMOUSLY: 'IS_AUTHENTICATED_ANONYMOUSLY',
    IS_AUTHENTICATED_FULLY: 'IS_AUTHENTICATED_FULLY',
    anonymousUser: 'anonymousUser',
    PRE_GROUP : 'GROUP_',
    PRE_AUTH : 'AUTH_'
})